<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :xs="12" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="公用经费支出表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwGyjfzcTable.loading" :columns="cwGyjfzcTable.columns"
          :dataSource="cwGyjfzcTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :rowSelection="true" :actionButton="true" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { getAction } from '@/api/manage'

export default {
  name: 'CwGyjfzcTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: { year: '' }, // 初始为空，由watch同步全局年度
      validatorRules: {
        year: [
          { required: true, message: '请选择年度!' },
        ],
        unit: [
          { required: true, message: '请选择单位!' },
        ],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwGyjfzc'],
      tableKeys: ['cwGyjfzc'],
      activeKey: 'cwGyjfzc',
      confirmLoading: false,
      // 公用经费支出表
      cwGyjfzcTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '支出类型',
            key: 'disbursementType',
            type: FormTypes.select,
            dictCode: "disbursement_type",
            width: "150px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '经济分类科目',
            key: 'jjflkm',
            type: FormTypes.sel_search,
            dictCode: "jjflkm",
            width: "150px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '财政',
            key: 'financial',
            type: FormTypes.input,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ pattern: "money", message: "${title}格式不正确" }],
          },
          {
            title: '财政/非财政',
            key: 'czFcz',
            type: FormTypes.select,
            dictCode: "cz_fcz",
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '小专项',
            key: 'xzx',
            type: FormTypes.input,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ pattern: "money", message: "${title}格式不正确" }],
          },
          {
            title: '金额',
            key: 'money',
            type: FormTypes.input,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '测算内容',
            key: 'ysnr',
            type: FormTypes.input,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '测算依据',
            key: 'calculationBasis',
            type: FormTypes.input,
            width: "100px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ]
      },
      url: {
        add: "/cw/cwGyjfzcTj/add",
        edit: "/cw/cwGyjfzcTj/edit",
        cwGyjfzc: {
          list: '/cw/cwGyjfzcTj/queryCwGyjfzcByMainId'
        },
        getByYear: '/cw/cwGyjfzcTj/list' // 复用体检表的年度查询接口，后续可自行修改
      },
      isManualChange: false // 标记是否手动修改过表单年度
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },
  created() {
    // 初始化时同步全局年度
    this.model.year = this.globalYear
  },
  methods: {
    addBefore() {
      console.log('执行新增初始化');
      this.cwGyjfzcTable.dataSource.splice(0);
      for (let i = 0; i < this.addDefaultRowNum; i++) {
        this.addDefaultRow();
      }
    },

    addDefaultRow() {
      const newRow = {
        _rowId: `row_${Date.now()}_${this.cwGyjfzcTable.dataSource.length}`,
        disbursementType: '',
        jjflkm: '',
        financial: '',
        czFcz: '',
        xzx: '',
        cwKeshi: '',
        money: '',
        ysnr: '',
        calculationBasis: ''
      };
      this.cwGyjfzcTable.dataSource.push(newRow);
      this.$forceUpdate();
    },

    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    editAfter() {
      this.$nextTick(() => { })
      if (this.model.id) {
        let params = { id: this.model.id }
        getAction(this.url.cwGyjfzc.list, params).then(res => {
          if (res.success) {
            this.cwGyjfzcTable.dataSource = res.result.records || []
          }
        }).finally(() => {
          this.cwGyjfzcTable.loading = false
        })
      }
    },

    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },

    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main,
        cwGyjfzcList: allValues.tablesValue[0].values,
      }
    },

    validateError(msg) {
      this.$message.error(msg)
    },

    close() {
      this.visible = false
      this.$emit('close')
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },

    async handleYearChange(year) {
      // 清空逻辑：未选择年度时，保留单位，清空其他数据
      if (!year) {
        this.model = { unit: this.model.unit }
        this.cwGyjfzcTable.dataSource = []
        return
      }

      // 加载状态：主表+子表同时加载
      this.confirmLoading = true
      this.cwGyjfzcTable.loading = true

      try {
        // 调用年度查询接口
        const yearResponse = await getAction(this.url.getByYear, { year })

        if (yearResponse.success && yearResponse.result.records.length > 0) {
          const mainRecord = yearResponse.result.records[0]
          // 主表数据回显：保留用户已选的unit和year，合并接口返回的其他字段
          this.model = {
            ...this.model,
            ...mainRecord
          }

          // 使用返回的mainId调用子表列表接口
          if (mainRecord.id) {
            const subResponse = await getAction(this.url.cwGyjfzc.list, {
              id: mainRecord.id
            })

            if (subResponse.success) {
              this.cwGyjfzcTable.dataSource = subResponse.result.records || []
            } else {
              this.$message.warning('获取公用经费支出表数据失败：' + (subResponse.message || '未知错误'))
              this.cwGyjfzcTable.dataSource = []
            }
          } else {
            this.$message.warning('未获取到关联ID，无法加载支出数据')
            this.cwGyjfzcTable.dataSource = []
          }
        } else {
          // 接口返回失败（如无数据），显示警告并清空子表
          this.$message.warning(yearResponse.message || '该年度暂无数据')
          this.cwGyjfzcTable.dataSource = []
          this.model.id = undefined;

        }
      } catch (error) {
        // 异常处理
        console.error('查询接口异常：', error)
        this.$message.error('查询失败，请刷新页面重试或联系管理员')
        this.cwGyjfzcTable.dataSource = []
      } finally {
        // 关闭加载状态（无论成功/失败）
        this.confirmLoading = false
        this.cwGyjfzcTable.loading = false
      }
    }
  }
}
</script>

<style scoped>
/* 调整分组表头样式 */
.j-editable-table thead .ant-table-cell[data-column-title="测算信息"] {
  background: #f5f7fa;
  /* 浅灰色背景 */
  font-weight: bold;
  /* 加粗字体 */
}
</style>